<template>
  <div class="chat-page">
    <!-- 左侧菜单保持不变 -->
    <div class="left-sidebar">
      <div class="header">
        <div class="avatar-title">
          <svg class="small-avatar" viewBox="0 0 100 100">
            <!-- 这里放置 SVG 内容 -->
            <circle cx="50" cy="50" r="45" fill="#FFE0B2"/>
            <circle cx="35" cy="40" r="5" fill="#795548"/>
            <circle cx="65" cy="40" r="5" fill="#795548"/>
            <path d="M 35 65 Q 50 80 65 65" stroke="#795548" fill="none" stroke-width="3"/>
            <!-- 可以添加更多 SVG 元素来美化头像 -->
          </svg>
          <h3>面试陪练官</h3>
        </div>
      </div>
      <div class="chat-history">
        <a-menu mode="inline" v-model:selectedKeys="selectedKeys">
          <!-- 通用面试专项 -->
          <a-sub-menu key="general">
            <template #title>
              <user-outlined />
              <span>通用面试专项</span>
            </template>
            <a-menu-item key="self-intro" @click="switchType('self-intro')" :disabled="isResponding">
              <user-outlined />
              自我介绍
            </a-menu-item>
            <a-menu-item key="resume" @click="switchType('resume')" :disabled="isResponding">
              <file-text-outlined />
              履历介绍
            </a-menu-item>
            <a-menu-item key="salary" @click="switchType('salary')" :disabled="isResponding">
              <fire-outlined />
              薪资谈判
            </a-menu-item>
          </a-sub-menu>

          <!-- 技术面试专项 -->
          <a-sub-menu key="technical">
            <template #title>
              <code-sandbox-outlined />
              <span>技术面试专项</span>
            </template>
            <a-menu-item key="basic" @click="switchType('basic')" :disabled="isResponding">
              <rocket-outlined />
              基础篇
            </a-menu-item>
            <a-menu-item key="scenario" @click="switchType('scenario')" :disabled="isResponding">
              <solution-outlined />
              场景题
            </a-menu-item>
            <a-menu-item key="project" @click="switchType('project')" :disabled="isResponding">
              <bar-chart-outlined />
              项目专项
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-content">
      <div class="chat-messages" ref="messagesRef">
        <!-- 遍历显示所有消息 -->
        <div v-for="(msg, index) in messages" 
             :key="index" 
             :class="['message', msg.type]">
          <template v-if="msg.type === 'ai'">
            <div class="message-bubble markdown-body">
              <div v-html="parseMarkdown(msg.content)"></div>
              <div v-if="isResponding && index === messages.length - 1" class="thinking-dots">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </template>
          <template v-else-if="msg.type === 'file'">
            <div class="message-bubble" v-if="msg.type === 'file'">
              <div class="file-preview">
                <template v-if="msg.fileType === 'pdf'">
                  <iframe
                    :src="msg.content"
                    class="pdf-preview"
                    type="application/pdf"
                  ></iframe>
                </template>
                <template v-else-if="msg.fileType === 'word'">
                  <div class="word-preview">
                    <file-outlined class="file-icon" />
                    <div class="file-info">
                      <span class="file-name">{{ msg.fileName }}</span>
                      <a :href="msg.content" target="_blank" class="preview-link">点击查看文档</a>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="message-bubble user-message">{{ msg.content }}</div>
          </template>
        </div>
      </div>
      
      <div class="chat-input">
        <div class="input-container">
          <!-- 添加文件预览区域 -->
          <div class="file-preview-area" v-if="uploadedFile || uploading">
            <div class="file-preview-card">
              <!-- Word文档图标 -->
              <div v-if="uploadedFile && uploadedFile.type === 'word'" class="file-icon word-icon">
                <svg viewBox="0 0 1024 1024" width="24" height="24">
                  <path d="M854.6 288.7L639.4 73.4c-6-6-14.2-9.4-22.7-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.6zM790.2 326H602V137.8L790.2 326z m1.8 562H232V136h302v216c0 23.2 18.8 42 42 42h216v494z" fill="currentColor"/>
                  <path d="M528.1 472h-32.2c-5.5 0-10.3 3.7-11.6 9.1L434.6 680l-46.1-198.7c-1.3-5.4-6.1-9.3-11.7-9.3h-35.4c-6.7 0-12.3 5.4-12.3 12.1v228c0 6.7 5.6 12.1 12.3 12.1h27.4c5.5 0 10.3-3.7 11.6-9.1l42.2-182.4 42.2 182.4c1.3 5.4 6.1 9.1 11.6 9.1h32.2c6.7 0 12.3-5.4 12.3-12.1v-228c0.1-6.7-5.5-12.1-12.2-12.1z" fill="currentColor"/>
                </svg>
              </div>
              <!-- PDF文档图标 -->
              <div v-if="uploadedFile && uploadedFile.type === 'pdf'" class="file-icon pdf-icon">
                <svg viewBox="0 0 1024 1024" width="24" height="24">
                  <path d="M854.6 288.7L639.4 73.4c-6-6-14.2-9.4-22.7-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.6zM790.2 326H602V137.8L790.2 326z m1.8 562H232V136h302v216c0 23.2 18.8 42 42 42h216v494z" fill="currentColor"/>
                  <path d="M497.9 585.3c0-31.3-39.3-83.7-87.8-163.2-46.6-76.2-78.8-120.5-96.8-133-2.7-1.9-5.6-3-8.7-3.2-4.4-0.3-8.1 1.2-11.1 4.5-2.9 3.2-4.3 7.1-4.2 11.7 0.3 8.9 5.9 22.5 16.7 40.7 10.8 18.2 27 41.1 48.7 68.5 20.8 26.4 35.4 47.3 43.8 62.8-38.9 47.7-62.2 86.4-69.8 115.9-5.5 21.3-3.8 38.4 5.2 51.2 5.9 8.5 14.4 13.1 25.5 14 32 2.6 74.1-31.9 126.3-103.5 19.5-5.3 41.8-10.2 66.9-14.7 40.3-7.2 65.8-11.2 76.5-11.9 18.2 32.5 36.2 48.8 54.1 49 13 0.1 22.9-6.7 29.6-20.3 6.5-13.2 5.7-25.5-2.2-36.7-7.9-11.2-22.5-16.9-43.8-17.2-13.9-0.2-32.8 2.1-56.5 6.8-47.1-58.4-70.9-101.2-71.5-128.5z m-94.6 195c-30.1 43.7-54.5 65.5-73.3 65.5-0.3 0-0.7 0-1.1-0.1-5.9-0.4-9.9-2.7-11.8-6.8-3.7-7.7-3.5-18.5 0.6-32.3 6.1-20.6 23.3-48.7 51.6-84.2 7.1 13.1 14.9 26.3 23.5 39.5 6.3 9.7 10.9 15.9 10.5 18.4z m82.8-207.8c1.1 13.6 13.1 38.3 36.1 74.1-26.8 3.1-47.2 6.2-61.4 9.1-7.1 1.5-13.7 3-19.9 4.5 4.6-7.8 9.5-15.7 14.7-23.7 15.7-24.1 26.5-43.4 30.5-64z m160.7 93.1c4.5 0 8.1 1.3 10.8 3.9 2.6 2.6 3.6 5.6 2.8 9-0.1 0.3-0.2 0.6-0.4 0.9-3.1 6.8-8.2 10.2-15.2 10.2-6.3 0-14.3-4.4-24.1-13.2-2.4-2.2-5.9-6.5-10.3-12.9 12.5-1.3 24.8 0.4 36.4 2.1z" fill="currentColor"/>
                </svg>
              </div>
              <!-- 上传中的loading图标 -->
              <loading-outlined v-if="uploading" spin class="file-icon loading-icon" />
              
              <div class="file-info">
                <span class="file-name">
                  {{ uploading ? '文件上传中...' : uploadedFile.fileName }}
                </span>
                <span class="file-size" v-if="uploadedFile">
                  {{ formatFileSize(uploadedFile.size) }}
                </span>
                <span class="upload-status" v-if="uploading">
                  正在解析文件，请稍候...
                </span>
              </div>
              
              <div class="file-actions" v-if="uploadedFile">
                <a :href="uploadedFile.url" target="_blank" class="preview-link">
                  <eye-outlined /> 预览
                </a>
                <a-button type="link" class="delete-btn" @click="removeFile">
                  <delete-outlined /> 删除
                </a-button>
              </div>
            </div>
          </div>

          <a-textarea
            v-model="inputMessage"
            placeholder="输入你的问题，按 Enter 发送，Shift + Enter 换行"
            :auto-size="{ minRows: 1, maxRows: 4 }"
            @keydown="handleKeyDown"
            class="chat-textarea"
          />
          <div class="input-actions">
            <div class="left-actions">
              <a-upload
                :customRequest="handleUpload"
                :showUploadList="false"
                :accept="'.pdf,.doc,.docx'"
                :beforeUpload="beforeUpload"
              >
                <a-tooltip title="支持 PDF、Word 格式">
                  <a-button class="action-btn upload-btn" type="text" :loading="uploading">
                    <file-outlined />
                    <span class="upload-text">上传简历</span>
                  </a-button>
                </a-tooltip>
              </a-upload>
            </div>
            <a-button 
              type="primary" 
              class="send-btn"
              :disabled="!inputMessage.trim() || isResponding"
              @click="() => sendMessage()"
            >
              <send-outlined />
              <span>{{ isResponding ? '回答中...' : '发送' }}</span>
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  PlusOutlined, 
  MessageOutlined,
  UserOutlined,
  FileTextOutlined,
  FireOutlined,
  RocketOutlined,
  SolutionOutlined,
  BarChartOutlined,
  CodeSandboxOutlined,
  PictureOutlined,
  FileOutlined,
  SendOutlined,
  EyeOutlined,
  DeleteOutlined,
  FileWordOutlined,
  FilePdfOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue'
import { request } from '@/utils/request'
import { marked } from 'marked'
import createDOMPurify from 'dompurify'

// 配置 marked 选项
marked.setOptions({
  breaks: true,
  gfm: true,
  headerIds: false
})

// 创建 DOMPurify 实例
const DOMPurify = createDOMPurify(window)

export default {
  name: 'AIChat',
  components: {
    UserOutlined,
    FileTextOutlined,
    FireOutlined,
    RocketOutlined,
    SolutionOutlined,
    BarChartOutlined,
    CodeSandboxOutlined,

    FileOutlined,
    SendOutlined,
    EyeOutlined,
    DeleteOutlined,

    LoadingOutlined
  },
  data() {
    return {
      loading: false, // 添加全局loading状态
      inputMessage: '',
      selectedKeys: [this.$route.params.type || 'self-intro'],
      messagesRef: null,
      ws: null,
      messages: [], // 存储聊天记录
      currentMessage: '', // 当前正在接收的消息
      currentType: '', // 前的面试类型
      isReceiving: false, // 是否正在接收消息
      userId: localStorage.getItem('loginId') || '', // 从localStorage获取userId
      openKeys: ['general', 'technical'], // 默认展开所有分组
      uploading: false, // 上传状态
      uploadedFile: null, // 存储上传的文件信息
      isResponding: false, // 添加AI是否正在回复的状态
      messageTimer: null, // 添加一个定时器
      lastMessageTime: null, // 记录最后一条消息的时间
    }
  },
  created() {
    // 从 Vuex store 获取 WebSocket 实例
    this.ws = this.$store.state.webSocket
    
    // 如果没有连接或连接已断开
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      // 不再主动调用connectWebSocket，而是等待父件的连接建立
      const checkConnection = setInterval(() => {
        this.ws = this.$store.state.webSocket
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          clearInterval(checkConnection)
          this.bindWebSocketEvents()
          // 获取路由参数中的type并开始对话
          const type = this.$route.params.type
          if (type) {
            this.startConversation(this.getTypeNumber(type))
          }
        }
      }, 500)
    } else {
      this.bindWebSocketEvents()
      // 获取路由参数中的type并开始对话
      const type = this.$route.params.type
      if (type) {
        this.startConversation(this.getTypeNumber(type))
      }
    }
  },
  beforeDestroy() {
    // 组件销毁前关闭WebSocket连接
    if (this.ws) {
      this.ws.close()
    }
    if (this.messageTimer) {
      clearTimeout(this.messageTimer)
    }
  },
  methods: {
    bindWebSocketEvents() {
      if (this.ws) {
        this.ws.onmessage = this.handleWebSocketMessage
      }
    },

    handleWebSocketMessage(event) {
      console.log('收到消息:', event.data)
      
      if (!event.data) return

      // 设置正在回复状态
      this.isResponding = true
      this.lastMessageTime = Date.now()

      if (this.messages.length === 0) {
        this.messages.push({
          type: 'ai',
          content: event.data
        })
        this.isReceiving = true
      } else if (!this.isReceiving) {
        this.messages.push({
          type: 'ai',
          content: event.data
        })
        this.isReceiving = true
      } else {
        this.messages[this.messages.length - 1].content = event.data
      }

      // 清除之前的定时器
      if (this.messageTimer) {
        clearTimeout(this.messageTimer)
      }

      // 设置新的定时器，如果1秒内没有新消息，认为回答结束
      this.messageTimer = setTimeout(() => {
        if (Date.now() - this.lastMessageTime >= 1000) {
          this.isResponding = false
          this.isReceiving = false
          this.messageTimer = null
        }
      }, 1000)
      
      this.$nextTick(() => {
        const messagesContainer = this.$refs.messagesRef
        if (messagesContainer) {
          messagesContainer.scrollTop = messagesContainer.scrollHeight
        }
      })
    },

    // 获取面试类型对应的数字
    getTypeNumber(type) {
      const typeMap = {
        'self-intro': '1',
        'resume': '2',
        'salary': '3',
        'basic': '4',
        'scenario': '5',
        'project': '6'
      }
      return typeMap[type] || '1'
    },
    
    // 修改 switchType 方法
    async switchType(type) {
      // 如果AI正在回复，不允许切换
      if (this.isResponding) {
        this.$message.warning('AI正在回答中，请稍候...')
        return
      }

      // 更新路由参数
      this.$router.replace({
        name: 'AIChat',
        params: { type }
      })
      
      // ���空消息表重置状态
      this.messages = []
      this.isReceiving = false // 重置接收状态
      
      // 确保WebSocket连接和事件处理正常
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        await new Promise((resolve) => {
          const checkConnection = setInterval(() => {
            this.ws = this.$store.state.webSocket
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
              clearInterval(checkConnection)
              this.bindWebSocketEvents() // 重新绑定事件处理
              resolve()
            }
          }, 500)
        })
      } else {
        this.bindWebSocketEvents() // 重新绑定事件处理
      }
      
      // 如果有已上传的简历，重新上传解析
      if (this.uploadedFile) {
        try {
          // 从URL获取文件
          const response = await fetch(this.uploadedFile.url)
          const blob = await response.blob()
          
          // 创建File对象
          const file = new File([blob], this.uploadedFile.fileName, { 
            type: this.uploadedFile.type === 'pdf' ? 'application/pdf' : 
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          })
          
          // 创建FormData
          const formData = new FormData()
          formData.append('file', file)
          formData.append('type', this.getTypeNumber(type))
          
          // 调用上传接口
          const res = await request.post('/subject/interview/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          
          if (res.code === 200) {
            // 更新文件URL
            this.uploadedFile.url = res.content
          } else {
            throw new Error(res.message || '重新解析失败')
          }
        } catch (error) {
          console.error('重新解析简历失败:', error)
          this.$message.error('重新解析简历失败，请重新上传')
          // 解析失败时清除文件信息
          this.uploadedFile = null
        }
      }
      
      // 重新开始对话
      await this.startConversation(this.getTypeNumber(type))
    },
    
    // 修改 startConversation 方法
    async startConversation(type) {
      this.currentType = type
      
      try {
        // 确保WebSocket连接已建立
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
          await new Promise((resolve) => {
            const checkConnection = setInterval(() => {
              this.ws = this.$store.state.webSocket
              if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                clearInterval(checkConnection)
                resolve()
              }
            }, 500)
          })
        }
        
        // WebSocket连接已建立，发送空消息开始对话
        this.isReceiving = false // 在发送息前重置状态
        await this.sendMessage('')
      } catch (error) {
        console.error('开始对话失败:', error)
        this.$message.error('开始对话失败,请重试')
      }
    },
    
    // 修改 sendMessage 方法
    async sendMessage(customMessage = null) {
      // 如果AI正在回复，不允许发送新消息
      if (this.isResponding && customMessage !== '') {
        this.$message.warning('AI正在回答中，请稍候...')
        return
      }

      const message = customMessage !== null ? customMessage : this.inputMessage
      if (!this.currentType || (typeof message === 'string' && !message.trim() && customMessage === null)) {
        return
      }
      
      // 检查WebSocket连接状态
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        // 等待WebSocket连接建立
        await new Promise((resolve) => {
          const checkConnection = setInterval(() => {
            this.ws = this.$store.state.webSocket
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
              clearInterval(checkConnection)
              resolve()
            }
          }, 500)
        })
      }
      
      try {
        if (message.trim()) {
          this.messages.push({
            type: 'user',
            content: message
          })
          this.$nextTick(() => {
            const messagesContainer = this.$refs.messagesRef
            if (messagesContainer) {
              messagesContainer.scrollTop = messagesContainer.scrollHeight
            }
          })
        }
        
        // 调用接口，添加文件URL参数
        await request.post('/subject/interview/mock', {
          type: this.currentType,
          message: message,
          fileUrl: this.uploadedFile ? this.uploadedFile.url : '' // 添加文件URL参数
        })
        
        // 清空输入框
        this.inputMessage = ''
        // 准备接收新消息
        this.isReceiving = false // 确保在发送新消息后重置接收状态
        this.currentMessage = ''
        
      } catch (error) {
        this.isReceiving = false
        console.error('发送消息失败:', error)
        this.$message.error('发送消息失败，请重试')
      }
    },
    
    // 添加 markdown 解析方法
    parseMarkdown(content) {
      if (!content) return ''
      return DOMPurify.sanitize(marked(content))
    },
    
    // 上传前校验
    beforeUpload(file) {
      // 检查文件类型
      const isValidType = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ].includes(file.type)
      
      if (!isValidType) {
        this.$message.error('只支持 PDF 或 Word 格式的文件！')
        return false
      }
      
      // 检查文件大小（限制为 10MB）
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB！')
        return false
      }
      
      return true
    },
    
    // 自定义上传方法
    async handleUpload({ file, onSuccess, onError }) {
      this.uploading = true
      this.loading = true // 开启全局loading
      
      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', this.currentType)
        
        const res = await request.post('/subject/interview/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (res.code === 200) {
          this.$message.success('简历上传成功')
          
          // 保存文件信息
          this.uploadedFile = {
            fileName: file.name,
            size: file.size,
            type: file.type.includes('pdf') ? 'pdf' : 'word',
            url: res.content
          }
          
          onSuccess(res)
        } else {
          this.$message.error('简历上传失败：' + res.message)
        }
      } catch (error) {
        this.$message.error('简历上传失败：' + (error.message || '未知错误'))
        onError(error)
      } finally {
        this.uploading = false
        this.loading = false // 关闭全局loading
      }
    },

    // 修改删除文件方法
    removeFile() {
      this.uploadedFile = null
      // // 知后端文件已被删除
      // this.sendMessage('我已删除了之前上传的简历')
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 添加回 handleKeyDown 方法
    handleKeyDown(e) {
      // 如果是回车键
      if (e.keyCode === 13) {
        // 阻止默认行为
        e.preventDefault()
        
        // 如果按住了 Shift 键，插入换行符
        if (e.shiftKey) {
          const cursorPosition = e.target.selectionStart
          const textBeforeCursor = this.inputMessage.substring(0, cursorPosition)
          const textAfterCursor = this.inputMessage.substring(cursorPosition)
          
          // 在光标��置插入换行符
          this.inputMessage = textBeforeCursor + '\n' + textAfterCursor
          
          // 设置新的光标位置
          this.$nextTick(() => {
            e.target.selectionStart = e.target.selectionEnd = cursorPosition + 1
          })
        } else {
          // 如果没有按 Shift，且输入框不空，则发送消息
          if (this.inputMessage.trim()) {
            this.sendMessage()
          }
        }
      }
    },
  },
  watch: {
    // 监听路由参数变化
    '$route.params.type': {
      handler(newType) {
        if (newType) {
          this.selectedKeys = [newType]
        }
      },
      immediate: true
    }
  },
  beforeRouteLeave(to, from, next) {
    // 只有当用户不是导到 AI 主页时才关闭连接
    if (!to.name.includes('AI')) {
      const ws = this.$store.state.webSocket
      if (ws) {
        ws.close()
        this.$store.commit('setWebSocket', null)
      }
    }
    next()
  }
}
</script>

<style scoped>
.chat-page {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
  overflow: hidden;
}

.left-sidebar {
  width: 260px;
  background: white;
  border-right: 1px solid #eef0f6;
  display: flex;
  flex-direction: column;
  padding: 16px;
  height: 100vh;
  overflow-y: auto;
  position: relative;
  z-index: 101;
}

.avatar-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.small-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.header {
  padding: 16px 0;
  border-bottom: 1px solid #eef0f6;
}

.new-chat-btn {
  margin: 16px 0;
  background: #eef4ff;
  border: none;
  color: #4080ff;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 24px;
  padding-bottom: 260px;
  overflow-y: auto;
  margin-bottom: 0;
}

.message {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.message.ai {
  margin-right: 100px;
}

.message .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.message.ai .message-bubble {
  background: #ffffff;
  padding: 16px 20px;
  border-radius: 16px;
  border: 1px solid #eef0f6;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  position: relative;
  transition: all 0.3s ease;
}

.message.ai .message-bubble:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.message.user {
  flex-direction: row-reverse;
  margin-left: 100px;
  margin-right: 0;
}

.message.user .message-bubble {
  background: #4080ff;
  color: white;
  padding: 16px 20px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(64, 128, 255, 0.15);
}

.chat-input {
  position: fixed;
  bottom: 0;
  left: 260px;
  right: 0;
  background: white;
  border-top: 1px solid #eef0f6;
  padding: 12px 24px;
  z-index: 100;
  height: auto;
  min-height: 120px;
  max-height: 240px;
  display: flex;
  flex-direction: column;
}

.input-container {
  flex: 1;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 12px;
  padding: 8px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.input-container:hover,
.input-container:focus-within {
  border-color: #4080ff;
  box-shadow: 0 2px 8px rgba(64, 128, 255, 0.1);
}

:deep(.chat-textarea) {
  flex: 1;
  border: none !important;
  padding: 4px 0 !important;
  resize: none !important;
  box-shadow: none !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  min-height: 24px !important;
  max-height: none !important;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  margin-top: 8px;
  border-top: 1px solid #f2f3f5;
  flex-shrink: 0;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  color: #4080ff;
  border-radius: 6px;
  transition: all 0.3s;
}

.upload-btn:hover:not(:global(.ant-btn-loading)) {
  background: #f0f7ff;
  color: #3574e8;
}

.upload-btn:global(.ant-btn-loading) {
  opacity: 0.7;
  cursor: not-allowed;
}

.upload-text {
  font-size: 14px;
  margin-left: 4px;
}

.send-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  height: 32px;
  padding: 0 12px;
  border-radius: 8px;
  font-size: 14px;
  background: #4080ff;
  border: none;
  transition: all 0.3s ease;
}

.send-btn:hover:not(:disabled) {
  background: #3574e8;
  transform: translateY(-1px);
}

.send-btn:disabled {
  background: #e5e6eb;
  cursor: not-allowed;
}

:deep(.send-btn .anticon) {
  font-size: 16px;
}

/* 输入框聚焦时的样式 */
:deep(.ant-input:focus) {
  box-shadow: none !important;
}

/* 调整输入框的内边距和行高 */
:deep(.ant-input) {
  width: 100% !important;
  padding: 8px 0;
  line-height: 1.6;
}

.message.user {
  flex-direction: row-reverse;
  margin-left: 80px;
  margin-right: 0;
}

.user-message {
  background: #4080ff !important;
  color: white;
}

.message-bubble {
  white-space: pre-wrap;
}

/* Markdown 样式 */
.markdown-body {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.markdown-body p {
  margin: 8px 0;
}

.markdown-body ul,
.markdown-body ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-body li {
  margin: 4px 0;
}

.markdown-body code {
  background-color: #f6f8fa;
  border-radius: 3px;
  padding: 2px 6px;
  font-family: Monaco, Consolas, monospace;
  font-size: 13px;
  color: #476582;
}

.markdown-body pre {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 12px 16px;
  margin: 12px 0;
  overflow-x: auto;
}

.markdown-body pre code {
  background-color: transparent;
  padding: 0;
  border-radius: 0;
}

/* 思考中的动画样式 */
.thinking-dots {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-left: 6px;
  vertical-align: middle;
}

.thinking-dots .dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #999;
  display: inline-block;
  animation: dotBounce 1.4s infinite ease-in-out;
}

.thinking-dots .dot:nth-child(1) {
  animation-delay: 0s;
}

.thinking-dots .dot:nth-child(2) {
  animation-delay: 0.2s;
}

.thinking-dots .dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dotBounce {
  0%, 80%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  40% {
    transform: translateY(-4px);
    opacity: 1;
  }
}

/* 消息气泡基础样式 */
.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  animation: messageSlideIn 0.3s ease-out;
}

.message.ai {
  margin-right: 20%;
}

.message.user {
  flex-direction: row-reverse;
  margin-left: 20%;
}

.message-bubble {
  background: #fff;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  max-width: 100%;
  position: relative;
}

.user .message-bubble {
  background: #1890ff;
  color: #fff;
}

/* 移除头像相关样式 */
.avatar {
  display: none;
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.file-preview {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.pdf-preview {
  width: 100%;
  height: 500px;
  border: none;
}

.word-preview {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.file-icon {
  font-size: 32px;
  color: #4080ff;
  margin-right: 16px;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.file-name {
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
}

.preview-link {
  color: #4080ff;
  font-size: 13px;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
}

/* 调整消息气泡样式以适应文件预览 */
.message-bubble {
  &:has(.file-preview) {
    max-width: 600px;
    padding: 0;
    overflow: hidden;
  }
}

.file-preview-area {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.file-preview-card {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  gap: 12px;
  min-height: 52px;
}

.file-icon {
  font-size: 24px;
  color: #4080ff;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.file-name {
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
}

.file-size {
  font-size: 12px;
  color: #86909c;
}

.file-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.preview-link {
  color: #4080ff;
  font-size: 13px;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 4px;
  
  &:hover {
    color: #3574e8;
  }
}

.delete-btn {
  color: #ff4d4f !important;
  padding: 0;
  height: auto;
  
  &:hover {
    color: #ff7875 !important;
    background: transparent !important;
  }
}

/* 调整输入框上方的边距 */
.input-container {
  display: flex;
  flex-direction: column;
}

.chat-textarea {
  flex: 1;
}

.file-icon {
  font-size: 24px;
}

.word-icon {
  color: #2b579a; /* Word蓝色 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.pdf-icon {
  color: #f40f02; /* PDF红色 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 调整SVG图标大小 */
.file-icon svg {
  width: 24px;
  height: 24px;
}

.loading-icon {
  color: #4080ff;
}

.upload-status {
  font-size: 12px;
  color: #86909c;
}

.file-preview-card {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  gap: 12px;
  min-height: 52px; /* 确保高度一致 */
}

/* 修改提交区域的样式 */
.submit-area {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding-top: 24px;
}

/* 移除原有的底部导航区域样式 */
.navigation-area {
  display: none; /* 或者直接删除这个类的样式 */
}

/* 导航按钮样式 */
.nav-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  height: 40px;
  padding: 0 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.nav-btn:not(:disabled):hover {
  background: #f0f7ff;
  border-color: #4080ff;
  color: #4080ff;
}

/* 禁用状态的按钮样式 */
.nav-btn[disabled] {
  cursor: not-allowed;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
  border-color: #d9d9d9;
}

/* 禁用状态的菜单项样式 */
:deep(.ant-menu-item-disabled) {
  cursor: not-allowed !important;
  opacity: 0.5;
}

/* 回答中的发送按钮样式 */
.send-btn.ant-btn-disabled {
  background: #f5f5f5;
  border-color: #d9d9d9;
  color: rgba(0, 0, 0, 0.25);
}
</style> 